package server.transceiver;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;

import server.command.receive.Command;
import server.exception.processor.ReceiveException;
import server.invoker.CommandInvoker;
import server.protocol.processor.ReceiveProtocolProcessor;
import server.protocol.processor.SendProtocolProcessor;
import server.resp.send.Resp;

public class Receiver implements Runnable{
	
	public Socket socket;
	
	public Receiver(Socket socket) {
		// TODO Auto-generated constructor stub
		this.socket = socket;
	}

	@Override
	public void run() {
		// TODO Auto-generated method stub
		try {
			analyzeCommand();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ReceiveException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public void analyzeCommand() throws IOException, ReceiveException {
		BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
		String commandStr = reader.readLine();
		ReceiveProtocolProcessor processor = new ReceiveProtocolProcessor();
		Command command = processor.process(commandStr);
		CommandInvoker commandInvoker = new CommandInvoker(command);
		Resp resp = commandInvoker.invoke();
		new Thread(new Sendor(resp, socket.getOutputStream())).start();
	}
}
